<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      p {
        height: 400px;
        border: solid;
        font-size: 3rem;
      }

      #top {
        width: 100px;
        height: 100px;
        display: none;
        justify-content: center;
        align-items: center;

        font-size: 3rem;
        background-color: yellow;
        position: fixed;
        bottom: 100px;
        right: 50px;
        cursor: pointer;
      }

      #top:hover {
        background-color: azure;
      }
    </style>
  </head>
  <body>
    <div id="top">TOP</div>
    <div id="box">
      <p>p1</p>
      <p>p2</p>
      <p>p3</p>
      <p>p4</p>
      <p>p5</p>
    </div>
    <script>
      const box = document.getElementById("box");
      const topBox = document.getElementById("top");
      window.onscroll = function () {
        //判断滚动的距离是否超过窗口的高度
        if (window.innerHeight - window.pageYOffset < 0) {
          // 设置top可见
          topBox.style.display = "flex";
        } else {
          // 设置top不可见
          topBox.style.display = "none";
        }

        if (
          document.documentElement.scrollHeight -
            window.innerHeight -
            window.pageYOffset <
          100
        ) {
          // 触底后的逻辑（根据需求写的）
          const p = document.createElement("p");
          p.innerHTML = "new P";
          box.append(p);
        }
      };

      topBox.onclick = function () {
        window.scrollTo({
          top: 0,
          left: 0,
          behavior: "smooth",
        });
      };
    </script>
  </body>
</html>
